package com.example.ds.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class RequestTimeFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(RequestTimeFilter.class);
    
    // 从配置文件中读取阈值（单位：毫秒）
    @Value("${request.time.threshold:1000}")
    private long timeThreshold;
    
    // 线程本地变量存储请求开始时间
    private static final ThreadLocal<Long> startTimeHolder = new ThreadLocal<>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        startTimeHolder.set(startTime);
        
        try {
            // 继续处理请求
            chain.doFilter(request, response);
        } finally {
            // 计算耗时
            long duration = System.currentTimeMillis() - startTime;
            startTimeHolder.remove();
            
            // 记录请求信息
            logRequestInfo((HttpServletRequest) request, duration);
        }
    }

    private void logRequestInfo(HttpServletRequest request, long duration) {
        String requestInfo = String.format("[%s] [%s] %s %s",
                request.getRemoteAddr(),
                request.getMethod(),
                request.getRequestURI(),
                request.getQueryString() != null ? "?" + request.getQueryString() : "");
        
        if (duration > timeThreshold) {
            logger.warn("⚠️ 请求超时 - {} - 耗时: {}ms (阈值: {}ms)", 
                    requestInfo, duration, timeThreshold);
        } else {
            logger.debug("✅ 请求完成 - {} - 耗时: {}ms", requestInfo, duration);
        }
    }
}